# _*_ coding:utf-8 _*_
# @Time  : 2023.10.20
# @Author: zizlee
import datetime
import time

import requests
from urllib3 import disable_warnings
disable_warnings()

CONFIGS = [
    {'id': 8171, 'plat': 'ruizhi', 'plat_id': 'R00021486', 'ruizhi_id': 8996, 'name': '裂解价差:柴油:ICE'},
    {'id': 8172, 'plat': 'ruizhi', 'plat_id': 'R00021487', 'ruizhi_id': 8995, 'name': '裂解价差:汽油:NYMEX'},
]


class UpdateWorker:

    def get_index_info_in_work(self, source_id):  # 获取指标在工作系统的详情
        url = 'https://210.13.218.130:9000/v1/datalib/table/'
        r = requests.get(url, params={'kw': source_id}, verify=False)
        index_obj = r.json()['data']['records']
        if len(index_obj) > 1:
            raise ValueError('查询ID有误，不止一条记录')
        if len(index_obj) < 1:
            raise ValueError('查询的数据指标不存在!{}'.format(source_id))
        return index_obj[0]

    def get_index_data_in_ruizhi(self, item):  # 获取在瑞智系统的数据
        start = item['enddate'] if item['enddate'] else item['startdate']
        end = datetime.date.today().strftime('%Y-%m-%d')
        url = 'http://210.13.218.130:9001/v1/admin/dataindex/intervalData/'
        r = requests.get(url, params={'index_id': item['ruizhi_id'], 'start': start, 'end': end})
        return r.json()['data']['rows']

    def save_data_to_work(self, iid: int, data_list):  # 将数据保存到工作系统
        url = 'https://210.13.218.130:9000/v1/datalib/table/update/'
        body_data = {'dataid': iid, 'row_value': data_list}
        r = requests.post(url, json=body_data, verify=False)
        print(r.json())

    def update(self):
        for row in CONFIGS:
            obj = self.get_index_info_in_work(source_id=row['plat_id'])
            row['startdate'] = obj['startdate']
            row['enddate'] = obj['enddate']
            records = self.get_index_data_in_ruizhi(item=row)
            # print(row, records[0], records[-1])
            self.save_data_to_work(iid=row['id'], data_list=records)
            time.sleep(1)


if __name__ == '__main__':
    handler = UpdateWorker()
    handler.update()

